#include "definirmode.h"
#include "ui_definirmode.h"
#include "fenserveur.h"

definirMode::definirMode(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::definirMode)
{
    ui->setupUi(this);
    r = new Reseau();
    dame = new DameChinoise();
    dame->setReseau(r);

    connect(r->getSocket(), SIGNAL(connected()), this, SLOT(connecte()));
    connect(r->getSocket(), SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(erreurSocket(QAbstractSocket::SocketError)));
    connect(r->getSocket(), SIGNAL(readyRead()), this, SLOT(donneesRecues()));
    test = 1;
}

definirMode::~definirMode()
{
    delete ui;
    delete r;
    delete dame;
}

void definirMode::connecte()
{
    pseudo = ui->pseudo->text();    
    r->envoyerDonnees(tr("&") + pseudo + tr("&"));
    dame->setLabelText(pseudo);
    dame->setPseudo(pseudo);
}
void definirMode::erreurSocket(QAbstractSocket::SocketError error)
{
    if(this->isVisible())
        ui->mesErreur->append(r->erreurSocket(error));
    if(dame->isVisible())
        dame->setMessage(r->erreurSocket(error));
}
void definirMode::donneesRecues()
{
    QString m = dame->donneesRecues();
    if(dame->isVisible())
    {
        if(test == 1)
        {
            r->envoyerDonnees(pseudo + conn);
            test = 0;
        }
        this->hide();
    }else{
        ui->mesErreur->append(m);
    }
}

void definirMode::on_okButton_clicked()
{
    conn = r->connecte(ui->serveurIP->text());
    ui->mesErreur->append(QString::fromUtf8("Connexion en cours à : ") + ui->serveurIP->text());
}

void definirMode::on_annulerButton_clicked()
{
    exit(1);
}
